﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class FirstQueryResult<TSource> : ObservableSingleQueryResultBase<TSource, TSource>
	{
		TSource _value;
		
		public FirstQueryResult(IEnumerable<TSource> source) : base(source)
		{
			OnSourceReset();
		}
		
		public override TSource Value
		{
			get{return _value;}
			set{throw new NotSupportedException();}
		}
		
		protected override void OnSourceReset()
		{
			foreach (var item in _attached)
			{
				DetachItem(item);
			}
			
			_attached.Clear();
			
			foreach (var item in _source)
			{
				AttachItem(item);
			}
			
			if(_sourceListGeneric != null && _sourceListGeneric.Count > 0)
			{
				_value=_sourceListGeneric[0];
			}
			else if(_sourceList != null && _sourceList.Count > 0)
			{
				_value = (TSource)_sourceList[0];
			}
			else
			{
				using(IEnumerator<TSource> enumerator=_source.GetEnumerator())
				{
					if(enumerator.MoveNext())
					{
						_value = enumerator.Current;
					}
					else
					{
						_value = default(TSource);
					}
				}
			}
		}
		
		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}
	}


}
